<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始答题时间筛选" label-width="130">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="问答类型" prop="topicType">
        <el-select v-model="queryParams.topicType" clearable @change="handleQuery">
          <el-option
            v-for="dict in sys_topic_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="versionNum">
        <el-select v-model="queryParams.versionNum" clearable @change="handleQuery">
          <el-option
            v-for="dict in sys_topic_version"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['business:exam:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['business:exam:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['business:exam:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:exam:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问答编号" align="center" prop="id" v-if="true"/>
      <el-table-column label="问答类型" align="center" prop="topicType">
        <template #default="scope">
          <dict-tag :options="sys_topic_type" :value="scope.row.topicType" />
        </template>
      </el-table-column>
      <el-table-column label="版本" align="center" prop="versionNum">
        <template #default="scope">
          <dict-tag :options="sys_topic_version" :value="scope.row.versionNum" />
        </template>
      </el-table-column>
      <el-table-column label="开始答题时间" align="center" prop="startAnswerTime" width="180">
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.startAnswerTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" @click="handleSelectTopic(scope.row)" v-hasPermi="['business:exam:examInfo']">查看详情</el-button>
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:exam:edit']">修改</el-button>-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:exam:remove']">删除</el-button>-->
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户问答对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="form" v-for="item in examTopic" :model="item" :rules="rules" label-width="80px" :key="item.id">

        <el-card>
          <el-form-item label="题干" prop="topicContent">
<!--            <el-input type="textarea" v-model="item.topicTitle" maxlength="255" show-word-limit readonly :rows="3"/>-->
            <editor v-model="item.topicTitle" readOnly="true"   :min-height="80"/>
          </el-form-item>
<!--          <el-form-item label="题目类型">-->
<!--            <el-radio-group v-model="item.topicType">-->
<!--              <el-radio-->
<!--                v-for="dict in dict.type.topic_type.slice(0,2)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.value"-->
<!--              >{{dict.label}}</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="选项:" required>-->

<!--          </el-form-item>-->
          <el-row>
            <el-col :span="6">
              <el-form-item label="状态:">
                <el-tag :type="item.status == 0?'danger':''">{{item.status == 0 ? "未答题" : "已答题"}}</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户回答:" v-if="item.userSelection">
                <div :key="itemSub.prefix"  v-for="(itemSub) in item.papTopicOptions" label-width="50px" class="question-item-label">
                  <span v-if="itemSub.prefix === item.userSelection">{{itemSub.content}}</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="回答时间 :" v-if="item.userSelection">
                <span type="info">{{item.quizTime}}</span>
              </el-form-item>
            </el-col>
<!--            <el-col :span="6">-->
<!--              <el-form-item label="回答结果:" v-if="item.correctStatus">-->
<!--                <el-tag :type="item.correctStatus == 0 ?'success':'danger'">{{item.correctStatus == 0 ? "正确" :  (item.correctStatus == 1 ? '错误' : '超时未答')}}</el-tag>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="6">-->
<!--              <el-form-item label="答案:" v-if="item.correct">-->
<!--                <el-tag type="success" effect="plain">{{item.correct}}</el-tag>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
          </el-row>
        </el-card>
        <el-form-item></el-form-item>
      </el-form>
<!--      <template #footer>-->
<!--        <div class="dialog-footer">-->
<!--          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>-->
<!--          <el-button @click="cancel">取 消</el-button>-->
<!--        </div>-->
<!--      </template>-->
    </el-dialog>
  </div>
</template>

<script setup name="Exam">
import { listExam, getExam, delExam, addExam, updateExam,getExamTopic } from "@/api/business/exam";

const { proxy } = getCurrentInstance();
const {sys_show_hide,sys_topic_type,sys_topic_version } = proxy.useDict("sys_show_hide","sys_topic_type","sys_topic_version");
const examList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const examTopic = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startAnswerTime: undefined,
    topicType: undefined
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    startAnswerTime: [
      { required: true, message: "开始答题时间不能为空", trigger: "blur" }
    ],
    topicType: [
      { required: true, message: "题目类型不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户问答列表 */
function getList() {
  loading.value = true;
  listExam(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    examList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function handleSelectTopic(row){
  const id = row.id || this.ids
  getExamTopic(id).then(response => {
    examTopic.value = response.data;
    console.log(response,'===========');
    for(var i = 0;i<response.data.length;i++){
      for(var j = 0;j<response.data[i].papTopicOptions.length;j++){
        if(response.data[i].userSelection === response.data[i].papTopicOptions[j].prefix){
          response.data[i].papTopicOptions[j].content
          let richTextRegex = /<(p)(.*?)>/g;
          if(richTextRegex.test(response.data[i].papTopicOptions[j].content)){
            response.data[i].papTopicOptions[j].content = extractTextFromRichContent(response.data[i].papTopicOptions[j].content);
          }
        }
      }
    }
    open.value = true;
    title.value = "查询用户问答详情";
  });
}
function extractTextFromRichContent(richContent) {
  // 创建一个新的DOM解析器
  const parser = new DOMParser();
  // 解析富文本内容为文档对象
  const doc = parser.parseFromString(richContent, 'text/html');
  // 提取文本内容
  return doc.body.textContent || '';
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    startAnswerTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    topicType: null
  };
  proxy.resetForm("examRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户问答";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getExam(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改用户问答";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["examRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateExam(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addExam(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户问答编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delExam(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/exam/export', {
    ...queryParams.value
  }, `exam_${new Date().getTime()}.xlsx`)
}

getList();
</script>
